# redis 归档主函数

from redis_ import RedisArchive
import json
import time
from guidangarch import ArchiveLogic
import mongo_

with open('../config.py', 'r', encoding="utf-8") as f:
    exec(f.read())

ovo_similarity = guidanginfo['ovo_similarity']
card_similarity = guidanginfo['card_similarity']
face_similarity = guidanginfo['face_similarity']
face_acvs_level_limit = guidanginfo['face_acvs_level_limit']
acvs_acvs_level_limit = guidanginfo['acvs_acvs_level_limit']

redis_client = RedisArchive()
logic_client = ArchiveLogic(redis_client, face_acvs_level_limit, acvs_acvs_level_limit)


def face_classify(facedet, hit_face_id, level_dic_x, level_dic_y):
    hit_face_img = redis_client.rdb_get_face(hit_face_id)
    # 读取档案信息 face_acvs
    if ('face_image_id' in hit_face_img) and ('detectFacev2' in hit_face_img):
        # 筛选模糊度  和角度
        if (int(hit_face_img['detectFacev2']) == 1) and (int(hit_face_img['detectFace']) == 1):
            hit_face_det = logic_client.blur_angle(hit_face_img)
            if hit_face_det:
                redis_client.rdb_get_face_acvsall(facedet, hit_face_id, level_dic_x, start=0, end=-1)
            elif facedet:
                redis_client.rdb_get_face_acvsall_null(hit_face_id, level_dic_y, start=0, end=-1)
        elif facedet:
            redis_client.rdb_get_face_acvsall_null(hit_face_id, level_dic_y, start=0, end=-1)


def main():
    conut = 1
    while True:
        conut += 1
        print('RUN2 runing', time.time())
        # try:
        # pop 获取一条数据
        ovn = redis_client.rdb_queue_pop_ovn()
        # pop free
        if ovn is None:
            # print('data empty:', conut)
            time.sleep(1)
            continue
        # 转换str-dict
        j = json.loads(ovn)
        # print(j)
        face_id = j['face_image_id']
        # 获取db13 img
        face_img = redis_client.rdb_get_face(face_id)
        # mongo_.insert_record_ebn(face_id, j)
        if (int(face_img['detectFacev2']) == 1) and (int(face_img['detectFace']) == 1):
            facedet = logic_client.blur_angle(face_img)
        else:
            facedet = False

        hit_card_list = []
        hit_card_dic = {}
        result = j['result']

        level_dic1 = {}  # hitface 98 正脸 +1  {acvs级别：[(acvs, hitfaceid)]}
        level_dic2 = {}  # hitface 98 侧脸 +3
        level_dic3 = {}  # hitface 97 正脸 +2
        level_dic4 = {}  # hitface 97 侧脸 +4
        ovo_not_satisfied_list = []
        for hit_face in result:
            hit_face_image_id = hit_face['hit_face_image_id']
            # 过滤自己
            if hit_face_image_id == j['face_image_id']:
                continue
            # 不满足一比一 10级
            if facedet and ('ovo_similarity' in hit_face) and (int(hit_face['ovo_similarity']) < ovo_similarity):
                ovo_not_satisfied_list.append(hit_face_image_id)
                continue
            # 证件照不参与归档
            if 'hit_repository_id' in hit_face:
                if card_similarity <= int(hit_face['similarity']):
                    card_id = hit_face_image_id
                    card_score = int(hit_face['similarity'])
                    hit_card_dic.update({card_id: card_score})
                    hit_card_list.append((card_id, card_score))
                    redis_client.rdb_queue_push_log_add_cardf(card_id, face_id, card_score)

                    card_has = redis_client.rdb_has_card_face(card_id, face_id)  # db8
                    if card_has:
                        redis_client.rdb_add_card_face(card_id, face_id)
                    if not card_has:
                        redis_client.rdb_zadd_card_face(card_id, face_id, card_score)

                    face_cardhas = redis_client.rdb_has_face_card(face_id, card_id)  # db9
                    if face_cardhas:
                        redis_client.rdb_add_face_card(face_id, card_id)
                    if not face_cardhas:
                        redis_client.rdb_zadd_face_card(face_id, card_id, card_score)
                    continue

            if int(hit_face['similarity']) >= 98:
                face_classify(facedet, hit_face_image_id, level_dic1, level_dic2)

            elif face_similarity <= int(hit_face['similarity']):
                face_classify(facedet, hit_face_image_id, level_dic3, level_dic4)

        redis_client.rdb_queue_push_log_card_dict(face_id, hit_card_dic)
        logic_client.face_acvs_level(face_id, facedet, level_dic1, level_dic2, level_dic3, level_dic4,
                                     hit_card_list, ovo_not_satisfied_list)
        # except Exception as e:
        #     print(e)
        #     time.sleep(10)
        #     continue


if __name__ == "__main__":
    main()
